package com.czy.owner.ui.business;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.api.ScopeBusinessApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.BusinessCategoryModel;
import com.czy.owner.entity.ScopeBusinessModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author: Raven
 * @date: 2017/12/8 8:52
 * @email: xiexiaomeng_001@163.com
 * @description: 业务范围新的页面
 */
public class BusinessScopeActivity extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tl_business)
    TabLayout tlBusiness;
    @BindView(R.id.view_pager_business)
    ViewPager viewPagerBusiness;

    private List<BaseFragment> fragmentList = new ArrayList<>();
    private BusinessFragmentAdapter mFragmentAdapter;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_business_scope;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.store_scope_business);
        getTableDataList();
//        initTable();
    }

    @Override
    protected void updateViews() {

    }

    /**
     * 初始化顶部Table
     */
    private void initTable( List<BusinessCategoryModel> datas){
        String storeId = SharedPreferencesUtils.getParam(BusinessScopeActivity.this,
                UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID,
                0) + "";
        try {
            datas.add(0,new BusinessCategoryModel(Integer.parseInt(storeId),"所有分类"));
            setDataList(datas);
        }catch (NumberFormatException e){

        }

    }

    private void setDataList(List<BusinessCategoryModel> cates) {

        if (cates.size() > 4) {
            tlBusiness.setTabMode(TabLayout.MODE_SCROLLABLE);
        } else {
            tlBusiness.setTabMode(TabLayout.MODE_FIXED);
        }
        for (int i = 0 ; i < cates.size() ; ++i){
            BusinessBaseFragment fragment = new BusinessBaseFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("cate_model",cates.get(i));
            fragment.setArguments(bundle);
            fragmentList.add(fragment);

        }
        mFragmentAdapter = new BusinessFragmentAdapter(getSupportFragmentManager(),fragmentList,cates);
        viewPagerBusiness.setAdapter(mFragmentAdapter);
        viewPagerBusiness.setOffscreenPageLimit(cates.size());
        tlBusiness.setupWithViewPager(viewPagerBusiness);
        viewPagerBusiness.setCurrentItem(0);
        viewPagerBusiness.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mFragmentAdapter.reloadFragment(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
//        changeTabLineWidth();
    }


    /*
修改下划线宽度
*/
    private void changeTabLineWidth() {
        Class<?> tablayout = tlBusiness.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tablayout.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
            LinearLayout ll_tab = null;
            try {
                ll_tab = (LinearLayout) tabStrip.get(tlBusiness);
                for (int i = 0; i < ll_tab.getChildCount(); i++) {
                    View child = ll_tab.getChildAt(i);
                    child.setPadding(0, 0, 0, 0);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((PhoneUtils.getPhoneWidth(this) - PhoneUtils.dip2px(this, 80f)) / 5, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                    //  new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                    params.setMargins(PhoneUtils.dip2px(this, 8f), 0, PhoneUtils.dip2px(this, 8f), 0);
                    child.setLayoutParams(params);
                    child.invalidate();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private void getTableDataList() {
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.SERVICE_CATEGORY);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(this));
        String storeId = SharedPreferencesUtils.getParam(BusinessScopeActivity.this,
                UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID,
                0) + "";
        params.addBodyParameter("storeId", storeId);
        MyLog.d("RAVEN","params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("RAVEN","result = " + result);
                String data = PhoneUtils.checkResponseFlag(BusinessScopeActivity.this,result);
                if(data!=null){
                    List<BusinessCategoryModel> dataList;
                    try {
                        Gson gson = new GsonBuilder().create();
                            dataList = gson.fromJson(data, new TypeToken<List<BusinessCategoryModel>>() {
                        }.getType());
                        initTable(dataList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("RAVEN","error = " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });

    }
}
